package controllers

import (
	"beegobegin/models"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"path"
	"strconv"
	"strings"
	"time"

	//"strconv"
)

type DBController struct {
	beego.Controller
}

func (this *DBController) InsertData() {
	o := orm.NewOrm()
	user := models.User{}

	user.Name = "小强"
	//user.Time = time.Now()
	user.Age = 21
	//执行插入
	n, err := o.Insert(&user)
	if err!=nil{
		fmt.Println("o.Insert error:", err)
	}
	fmt.Println("添加成功:",n)
	bytes, _ := json.Marshal("添加成功")
	this.Ctx.WriteString(string(bytes))
}

var Users []models.User
var User []models.User
//var UsersMap []orm.Params
//var UsersList []orm.ParamsList

func (this *DBController) GetUsers() {
	o := orm.NewOrm()

	//var users []models.User
	//qb, _ := orm.NewQueryBuilder("mysql")
	//qb.Select("user.id", "user.name","age","number","email").From("user").LeftJoin("phone").On("user.id=phone.user_id").LeftJoin("profile").On("profile.user_id=user.id")
	//sql:=qb.String()
	//o.Raw(sql).QueryRows(&users)
	//beego.Info(users)

	//使用原生查询
	//o.Raw("select id, name from user").QueryRows(&Users)

	//传入参数数据库中表名或者模型对象
	//user := new(models.User)
	//传入表名为mysql中表名或结构体名均可
	o.QueryTable("User").All(&Users)
	//for i, user:= range Users {
	for i, _:= range Users {
		//o.QueryTable("User").RelatedSel("Profile").Filter("Profile__Id",user.Id).All(&User)
		//beego.Info(User)
		o.LoadRelated(&Users[i], "Profile")
		o.LoadRelated(&Users[i], "Phone",0,2)
		o.LoadRelated(&Users[i], "City")
	}



	//o.QueryTable("User").All(&Users)
	//all, _ := o.QueryTable(user).All(&Users)
	//beego.Info(all)
	//指定字段,字段名为结构体模型中名，All指定字段，其他字段也返回，但返回数据类型默认值
	//o.QueryTable(user).All(&Users,"Id", "Name")

	//values
	//o.QueryTable(user).Values(&UsersMap,"Id", "Name", "Age")
	//for _, users := range UsersMap {
	//	beego.Info(users["Id"],users["Name"])
	//}

	//ValuesList
	//o.QueryTable(user).ValuesList(&UsersList,"Name")
	//allbytes, _ := json.Marshal(Users)
	//this.Ctx.WriteString(string(allbytes))

	this.Data["json"] = Users
	//this.Data["json"] = UsersMap
	this.ServeJSON()

	//mapbytes, _ := json.Marshal(UsersMap)
	//this.Ctx.WriteString(string(mapbytes))
	//listbytes, _ := json.Marshal(UsersList)
	//this.Ctx.WriteString(string(listbytes))
}

func (this *DBController) GetUser() {
	o := orm.NewOrm()
	user:=models.User{}
	//根据id查不需要指定字段
	//ids :=this.Ctx.Input.Param(":id")
	//id, _ := strconv.ParseInt(ids, 10, 0)
	//user.Id = int(id)
	//o.Read(&user)

	//根据其他字段查，需要指定字段
	user.Name = "go"
	o.Read(&user,"name")

	bytes, _ := json.Marshal(user)
	this.Ctx.WriteString(string(bytes))
}

func (this *DBController) UpdateUser() {
	o := orm.NewOrm()
	user:=models.User{}
	//根据id更新不需要指定字段
	ids :=this.Ctx.Input.Param(":id")
	id, _ := strconv.ParseInt(ids, 10, 0)
	user.Id = int(id)

	//根据其他字段更新可实现，需要指定字段，但是url如果有:id，不存在的id也能更新
	//user.Name = "golang"
	//err := o.Read(&user, "name")
	err := o.Read(&user)
	var jsonBytes []byte
	if err!=nil{
		jsonBytes, _ = json.Marshal("user不存在")
		this.Ctx.WriteString(string(jsonBytes))
		return
	}
	user.Name = "go"
	// update默认更新所有字段，可以指定更新字段
	_, err = o.Update(&user, "Name")
	if err!=nil{
		jsonBytes, _ = json.Marshal("更新失败")
		this.Ctx.WriteString(string(jsonBytes))
		return
	}

	jsonBytes, _ = json.Marshal(user)
	this.Ctx.WriteString(string(jsonBytes))
}

func (this *DBController) Del() {
	o := orm.NewOrm()
	user := models.User{}
	user.Id = 2
	_, err := o.Delete(&user)
	if err!=nil{
		bytes, _ := json.Marshal("删除失败")
		this.Ctx.WriteString(string(bytes))
	}
	bytes, _ := json.Marshal(user)
	this.Ctx.WriteString(string(bytes))
}

var s = ".JPG.Webp.BMP.PCX.TIF.GIF.JPEG.TGA.EXIF.FPX.SVG.PSD.CDR.PCD.DXF.UFO.EPS.AI.PNG.HDRI.RAW.WMF.FLIC.EMF.ICO"

func (this *DBController) ImgUpload() {
	/*
	html中enctype 必须为 multipart/form-data
	postman测试Content-Type置为空
	*/
	file, header, err := this.GetFile("filename")
	if err!=nil{
		errStr := "图片上传错误" + err.Error()
		jsonBytes, _ := json.Marshal(errStr)
		this.Ctx.WriteString(string(jsonBytes))
		return
	}
	defer file.Close()
	//获取后缀名
	fileext := path.Ext(header.Filename)
	beego.Info(strings.ToUpper(fileext))
	beego.Info(strings.ToUpper(s))
	if ok:=strings.Contains(strings.ToUpper(s), strings.ToUpper(fileext)); !ok{
		jsonBytes, _ := json.Marshal("图片格式错误")
		this.Ctx.WriteString(string(jsonBytes))
		return
	}
	//限制文件大小
	if header.Size > 5 *1024*1024{
		jsonBytes, _ := json.Marshal("图片太大，请传小于5M的图片")
		this.Ctx.WriteString(string(jsonBytes))
		return
	}

	//3.需要对文件重命名，防止文件名重复
	fileName := strconv.FormatInt(time.Now().Unix(), 10)+ fileext
	err = this.SaveToFile("filename", "./static/img/"+fileName)
	if err!=nil{
		jsonBytes, _ := json.Marshal("图片上传失败"+err.Error())
		this.Ctx.WriteString(string(jsonBytes))
		return
	}
	jsonBytes, _ := json.Marshal("图片上传成功")
	this.Ctx.WriteString(string(jsonBytes))
}
